package com.aiju.cash.ui.good;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Good;
import com.aiju.bean.GoodsType;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.GoodApi;
import com.aiju.cash.ui.enter.util.EnterHelper;
import com.aiju.cash.util.ImageDialogUtil;
import com.aiju.common.ActivityStack;
import com.aiju.common.ImageLoader;
import com.aiju.utils.CheckUtil;
import com.aiju.utils.EmojiFilter;
import com.aiju.utils.L;
import com.aiju.utils.T;
import com.aiju.utils.Util;
import com.aiju.widgit.dialog.ListDialog;
import com.aiju.widgit.layout.SettingItemRadioButton;
import com.aiju.widgit.layout.SettingItemTextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2016-11-17 16:32
 * @version: V1.0
 * @Description: 商品添加
 */
public class GoodAddActivity extends BaseTitleActivity {

    public static final int REQUEST_CODE = 0;

    private final static int PHOTO_REQUEST = 1;

    private String goodTypeId;
    private String unit = "件";

    private TextView typeTextView;
    private ImageView addPicImageView;

    private EditText nameEditText, codeEditText, priceEditText;

    private File picFile;
    private Bitmap bitmap = null;

    private String goodId;
    //  private int position;
    private int type;
    private Good good;

    private String scanResult;

    private TextView pic;

    private SettingItemRadioButton radioButton;

    private TextView ke;

    private List<String> msg = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_good_add);
        setCenterTitle("新增商品");

        msg.add("500克");
        msg.add("千克");
        msg.add("两");
        msg.add("斤");
        addPicImageView = (ImageView) findViewById(R.id.iv_good_add_pic);
        nameEditText = (EditText) findViewById(R.id.et_good_add_name);
        codeEditText = (EditText) findViewById(R.id.et_good_add_code);
        priceEditText = (EditText) findViewById(R.id.et_good_add_price);
        typeTextView = (TextView) findViewById(R.id.tv_good_add_type);
        pic = (TextView) findViewById(R.id.tv_good_add_pic);
        ke = (TextView) findViewById(R.id.tv_ke);
        ke.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showUnitDialog();
            }
        });
        radioButton = (SettingItemRadioButton) findViewById(R.id.setr_good);
        radioButton.getleftView().getPaint().setFakeBoldText(true);
        radioButton.setRadio1Text("称重");
        radioButton.setRadio2Text("计件");
        radioButton.setRadioGroupCheck("2");
        radioButton.setChangeListener(new SettingItemRadioButton.OnChangeListener() {
            @Override
            public void change(String item) {
                if (item.equals("1")) {
                    ke.setVisibility(View.VISIBLE);
                    unit = "500克";
                } else {
                    ke.setVisibility(View.GONE);
                    unit = "件";
                }
            }
        });

        type = getIntent().getIntExtra("type", 0);
        //position = getIntent().getIntExtra("position", 0);
        if (type == 1) {//1.详情，修改   2.添加
            setCenterTitle("商品详情");
            goodId = getIntent().getStringExtra("goodId");
            ((TextView) findViewById(R.id.tv_good_tip_name)).setText("商品名称");
            ((TextView) findViewById(R.id.tv_good_tip_type)).setText("商品分类");
            ((TextView) findViewById(R.id.tv_good_tip_price)).setText("商品价格");
            pic.setText("点击更换商品图片");
            goodDetails();
        } else {//添加

            //GoodsType goodsType = GoodManager.getInstance(this).getGoodsTypes().get(position);
            GoodsType goodsType = (GoodsType) getIntent().getSerializableExtra("position");

            goodTypeId = goodsType.getId();
            typeTextView.setText(goodsType.getName());
            pic.setText("点击添加商品图片");
        }
        // KeyBoardUtils.openKeybord(nameEditText, this);
        findViewById(R.id.rl_good_add_pic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
/*                Intent intent = new Intent(GoodAddActivity.this, SelectActivity.class);
                startActivityForResult(intent, PHOTO_REQUEST);*/
                ImageDialogUtil.showSelectPicDialog(GoodAddActivity.this);
            }
        });

        findViewById(R.id.tv_good_add_type).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodAddActivity.this, GoodCategoryActivity.class);
                intent.putExtra("type", 1);
                startActivityForResult(intent, 100);
            }
        });

        findViewById(R.id.iv_gcode_code).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(GoodAddActivity.this, GoodCodeActivity.class);
                startActivityForResult(intent, 101);
            }
        });

        nameEditText.setFilters(new InputFilter[]{
                new EmojiFilter()
        });
        priceEditText.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (source.equals(".") && dest.toString().length() == 0) {
                    return "0.";
                }
                if (dest.toString().contains(".")) {
                    int index = dest.toString().indexOf(".");
                    int mlength = dest.toString().substring(index).length();
                    if (mlength == 3) {
                        return "";
                    }
                }

                StringBuilder builder = new StringBuilder(dest.toString());
                builder.append(source);
                Double d = Double.valueOf(builder.toString());
                if (d > 200000) {
                    T.ToastShort("商品单价不能超过20万");
                    return "";
                }
                return source;
            }
        }});

        findViewById(R.id.btn_good_add_save).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = nameEditText.getText().toString();
                String code = codeEditText.getText().toString();
                String price = priceEditText.getText().toString();

                if (TextUtils.isEmpty(name)) {
                    T.ToastShort("请输入商品名称");
                    return;
                } else if (TextUtils.isEmpty(price)) {
                    T.ToastShort("请输入商品价格");
                    return;
                } else if (TextUtils.isEmpty(goodTypeId)) {
                    T.ToastShort("请选择商品类型");
                    return;
                } else {
                    if (!CheckUtil.checkGoodName(name)) {
                        T.ToastShort("商品名称仅支持12个字符长度的汉字、数字以及英文");
                        return;
                    }
                    if (type == 1) {//修改商品
                        if (picFile != null) {
                            uploadPic(picFile, name, price, code);
                        } else {
                            update(name, price, code, good.getImageUrl());
                        }

                    } else { //新增商品
                        if (picFile != null) {
                            uploadPic(picFile, name, price, code);
                        } else {
                            savaGood(name, price, code, "");
                        }
                    }
                }
            }
        });
    }

    /**
     * 显示商品单位
     */
    private void showUnitDialog() {
        new ListDialog(this)
                .setLayoutParams()
                .setData(msg)
                .setOnItemOnClick(new ListDialog.OnItemOnClick() {
                    @Override
                    public void click(String item, int position) {
                        unit = item;
                        ke.setText("/ " + item);
                    }
                }).show();
    }

    /**
     * 商品修改
     */
    private void update(final String name, final String price, final String code, String imageUrl) {
        if (Util.isEmpty(good)) {
            return;
        }
        mDialogHelper.showLoadingProgressDialog();
        new GoodApi().goodUpdate(good.getId(), mUser.getStoreId(), mUser.getToken(), name, code, price, unit,
                goodTypeId, imageUrl, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        T.ToastNetError();
                        mDialogHelper.dismissProgressDialog();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        mDialogHelper.dismissProgressDialog();
                        DataJson dataJson = new DataJson(response);
                        if (dataJson.isSuccess()) {
                            finish();
                            ActivityStack.finish(ActivityStack.findActivity(GoodActivity.class.getName()));
                            startActivity(GoodActivity.class);
                        } else {
                            T.ToastShort(dataJson.getMsg());
                        }
                    }
                });
    }

    /**
     * 上传图片
     *
     * @param name
     * @param price
     * @param code
     */
    private void uploadPic(File file, final String name, final String price, final String code) {
        new GoodApi().uploadGoodImage(file, mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    try {
                        String pic = dataJson.getJsonObject().getString("data");
                        if (type == 1) {
                            update(name, price, code, pic);
                        } else {
                            savaGood(name, price, code, pic);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }


    /**
     * 商品详情
     */
    private void goodDetails() {
        mDialogHelper.showLoadingProgressDialog();
        new GoodApi().goodDetails(goodId, mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                mDialogHelper.dismissProgressDialog();
                T.ToastNetError();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    good = new Gson().fromJson(dataJson.getData().toString(), new TypeToken<Good>() {
                    }.getType());
                    nameEditText.setText(good.getName());
                    nameEditText.setSelection(good.getName().length());
                    priceEditText.setText(good.getPrice());
                    codeEditText.setText(TextUtils.isEmpty(good.getCode()) ? " " : good.getCode());
                    typeTextView.setText(good.getGoodsTypeName());
                    goodTypeId = good.getGoodsTypeId();
                    scanResult = good.getCode();
                    if (!Util.isEmpty(good.getImageUrl())) {
                        ImageLoader.loadImage(addPicImageView, good.getImageUrl());
                    }
                    if (good.isWeighGood()) {
                        radioButton.setRadioGroupCheck("1");
                        unit = good.getUnit();
                        ke.setText("/ " + unit);
                    }

                    if (!mUser.getRole().equals("0") || !mUser.getShop().getShopType().equals("0")) {
                        nameEditText.setEnabled(false);
                        priceEditText.setEnabled(false);
                        codeEditText.setEnabled(false);
                        typeTextView.setOnClickListener(null);
                        typeTextView.setTextColor(Util.getColor(R.color.color_999999));
                        typeTextView.setCompoundDrawables(null, null, null, null);

                        findViewById(R.id.iv_gcode_code).setVisibility(View.GONE);
                        findViewById(R.id.view_lins).setVisibility(View.GONE);
                        findViewById(R.id.tv_good_add_pic).setVisibility(View.GONE);
                        findViewById(R.id.btn_good_add_save).setVisibility(View.GONE);
                        findViewById(R.id.rl_good_add_pic).setOnClickListener(null);
                        ke.setCompoundDrawables(null, null, null, null);
                        ke.setOnClickListener(null);

                        radioButton.setVisibility(View.GONE);
                        SettingItemTextView type = (SettingItemTextView) findViewById(R.id.tv_setr_good);
                        type.setVisibility(View.VISIBLE);
                        type.getRightView().setTextColor(Util.getColor(R.color.color_999999));
                        type.getleftView().getPaint().setFakeBoldText(true);
                        type.getleftView().setText("记重方式");
                        type.setRightText(good.isWeighGood() ? "称重" : "计件");
                    }
                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }

    /**
     * 保存商品
     *
     * @param name
     * @param price
     * @param code
     * @param imageUrl
     */
    private void savaGood(String name, String price, String code, String imageUrl) {
        mDialogHelper.showLoadingProgressDialog();
        new GoodApi().goodSava(mUser.getStoreId(), name, goodTypeId, price, unit, mUser.getToken(), code, imageUrl, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
                mDialogHelper.dismissProgressDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    finish();
                    ActivityStack.finish(ActivityStack.findActivity(GoodActivity.class.getName()));
                    startActivity(GoodActivity.class);
                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        //KeyBoardUtils.closeKeybord(nameEditText, this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == data) {
            return;
        }
        picFile = EnterHelper.onActivityResult(addPicImageView, requestCode, resultCode, data);
        //商品分类
        if (requestCode == 100) {
            Bundle bundle = data.getExtras();
            if (null != bundle) {
                goodTypeId = bundle.getString("typeId");
                typeTextView.setText(bundle.getString("typeName"));
                L.d(goodTypeId);
            }
        }

        //条形码
        if (resultCode == 101) { //RESULT_OK = -1
            Bundle bundle = data.getExtras();
            scanResult = bundle.getString("code");
            codeEditText.setText(scanResult);
        }
    }

    @Override
    protected void onDestroy() {
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
        super.onDestroy();
    }
}
